package com.ycx.ycxmybatismanagement.filter;


import com.ycx.ycxmybatismanagement.util.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Slf4j
//@WebFilter(urlPatterns = "/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //初始化方法, web服务器启动, 创建Filter实例时调用, 只调用一次
        log.info("filter init");
    }

    @Override
    //拦截到请求时,调用该方法,可以调用多次
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
       HttpServletRequest request = (HttpServletRequest)req;
       HttpServletResponse response = (HttpServletResponse)res;
        StringBuffer reqUrl = request.getRequestURL();
        if (reqUrl.indexOf("/login")>=0){
            chain.doFilter(req,res);
            return;
        }
        String token = request.getHeader("token");
        if (!StringUtils.hasLength(token)){
            //表示没有值
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
        }

        if(!StringUtils.hasLength(token)){
            // 禁止访问，跳转到登录
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return;
        }
        // 校验token
        try{
            Claims claims = JwtUtils.parseJWT(token);
            // token是合法的
            // 放行
            chain.doFilter(request, response);
        }catch(Exception e){
            log.error(e.getMessage(), e);
            // 禁止访问，跳转到登录
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return;
        }
    }

    @Override
    public void destroy() {
        //销毁方法, web服务器关闭时调用, 只调用一次
        log.info("filter destroy");

    }
}
